<?php
/**
 * Created by PhpStorm.
 * User: t
 * Date: 2024/6/8
 * Time: 10:16
 * * @copyright: ©2024 永州微聚商 网络科技有限公司
 * @link: https://www.weiJuyunke.com
 */

namespace app\common\model;

use think\Model;
class Menu extends Model
{
    protected $name = "menu";

    public function getTreeMenu()
    {
        $tree = $this->order('parentId asc, sortNumber asc')->select()->toArray();
        return $this->makeTree($tree);
    }

    // 递归构建树
    public function makeTree($array, $parent_id = 0)
    {
        $tree = array();
        foreach($array as $key => $value) {
            if($value['parentId'] == $parent_id) {
                $value['children'] = $this->makeTree($array, $value['id']);
                $tree[] = $value;
                unset($array[$key]);
            }
        }
        return $tree;
    }

    public function getMenu($roleId){

        $data =[];
        if (!$data){
            $data = $this->where(['deleted' => 0])->order('sortNumber','asc')->select()->toArray();
        }
        if (!in_array(1,$roleId) ){
            $roleMenuModel  = new RoleMenu();
            $roleMenu =  $roleMenuModel->where('role_id' ,'in',$roleId )->select()->toArray();
            $menuId = array_column($roleMenu,'menuId');
            foreach ($data as $key => $value){
                if (!in_array($value['menuId'],$menuId)){
                    unset($data[$key]);
                }
            }
        }

        return  array_values($data);
    }
}
